namespace SimpleWebServices.Web
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Web;
    using SimpleWebServices.Configuration;
    using SimpleWebServices.Models;

    public static class HttpRequestBaseTenantExtensionMethods
    {
        public static RelativeUri TenantContentPath(this HttpRequestBase request)
        {
            RelativeUri result = null;

            string tenant = request.TenantPath(0);
            if (!string.IsNullOrEmpty(tenant) && request.Path.Length > tenant.Length + 1)
            {
                result = request.Path.Substring(tenant.Length);
            }

            return result;
        }

        public static RelativeUri TenantPath(this HttpRequestBase request)
        {
            return request.TenantPath(0);
        }

        [SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "URIs are normalised to lower case.")]
        public static RelativeUri TenantPath(this HttpRequestBase request, int index)
        {
            if (null == request)
            {
                throw new ArgumentNullException("request");
            }
            else if (0 > index)
            {
                throw new ArgumentOutOfRangeException("index");
            }

            RelativeUri result = null;

            string path = request.Path;
            if (null != path && 1 < path.Length)
            {
                string[] parts = path.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                if (index < parts.Length && 0 != parts[index].Length)
                {
                    result = "/" + parts[index].ToLowerInvariant();
                }
            }

            return result;
        }

        public static AbsoluteUri TenantUrn(this HttpRequestBase request)
        {
            AbsoluteUri value = null;

            RelativeUri path = request.TenantPath();
            if (null != path)
            {
                value = RepositoryConfiguration.ToUrn<Tenant>("tenant" + path);
            }

            return value;
        }
    }
}